<template>
    <div class="user-page">

        <!-- 返回首页按钮 -->
        <div class="back-home">
            <button @click="goHome">返回首页</button>
        </div>

        <h2>用户信息</h2>
        <div class="user-details">
            <p><strong>用户名：</strong>{{ user.username }}</p>
            <p><strong>手机号：</strong>{{ user.phone }}</p>
        </div>

        <div class="action-section">
            <button @click="toggleSection('editInfo')">修改用户信息</button>
            <button @click="toggleSection('changePassword')">修改密码</button>
            <button @click="logout">退出登录</button> <!-- 退出登录按钮 -->
        </div>

        <div v-if="showSection === 'editInfo'" class="form-section">
            <h3>修改用户信息</h3>
            <input v-model="editUser.phone" type="text" placeholder="手机号" />
            <input v-model="editUser.username" type="text" placeholder="用户名" />
            <button @click="updateUserInfo">保存</button>
        </div>

        <div v-if="showSection === 'changePassword'" class="form-section">
            <h3>修改密码</h3>
            <input v-model="password.phone" type="number" placeholder="手机号" />
            <input v-model="password.old" type="password" placeholder="当前密码" />
            <input v-model="password.new" type="password" placeholder="新密码" />
            <button @click="changePassword">保存</button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from 'vue';
import axios from 'axios';

// 返回首页功能
const goHome = () => {
    window.location.href = '/'; // 替换为你的首页路径
};

// 用户信息状态
const user = reactive({
    username: '',
    phone: '',
});

// 用于编辑用户信息
const editUser = reactive({
    username: '',
    phone: '',
});

// 修改密码状态
const password = reactive({
    phone: '',
    old: '',
    new: '',
});

// 控制显示的部分
const showSection = ref('');

// 切换显示部分
const toggleSection = (section: string) => {
    showSection.value = showSection.value === section ? '' : section;
};

// 更新用户信息
const updateUserInfo = async () => {
    try {
        const token = localStorage.getItem('Authorization');
        if (!token) {
            alert('请先登录');
            return;
        }

        // 获取当前登录用户的信息
        const response1 = await axios.get('http://127.0.0.1:8080/getLoginUser', {
            headers: {
                'Authorization': `${token}`, // 添加 Authorization 头
            }
        });

        const uid = response1.data.data.uid;

        // 准备更新的用户信息
        const updatedUser = {
            username: editUser.username,
            phone: editUser.phone,
            uid: uid,
        };

        // 发送更新请求
        const response = await axios.put('http://127.0.0.1:8080/user/update', updatedUser, {
            headers: {
                'Authorization': `${token}`, // 添加 Authorization 头
            }
        });

        if (response.data.code === 200) {
            // 更新成功，更新界面上的数据
            user.username = editUser.username;
            user.phone = editUser.phone;
            alert('用户信息更新成功！');
        } else {
            alert(response.data.msg || '用户信息更新失败！');
        }
    } catch (error) {
        console.error(error);
        alert('用户信息更新失败！');
    }
};


// 修改密码
const changePassword = async () => {
    const phone = password.phone; // 请替换成实际的手机号
    const oldPassword = password.old;
    const newPassword = password.new;

    // 从 localStorage 获取存储的 token
    const token = localStorage.getItem('Authorization');  // 假设 token 存储在 localStorage 中

    if (!token) {
        alert("请先登录！");
        return;
    }

    if (phone != user.phone) {
        alert("手机号与当前用户不符！");
        return;
    }

    try {
        const response = await axios.put('http://127.0.0.1:8080/user/recoverPassword', null, {
            headers: {
                'Authorization': `${token}`, // 添加 Authorization 头
            },
            params: {
                phone: phone,
                oldPassword: oldPassword,
                newPassword: newPassword,
            }
        });
        if (response.data.code === 200) {

            alert('密码修改成功！请重新登录');
            logout(); // 密码修改成功后退出登录

        } else {
            alert(response.data.msg || '密码修改失败！');
        }
    } catch (error) {
        console.error(error);
        alert('密码修改失败！');
    }
};

// 获取用户信息
const getUserInfo = async () => {
    try {
        const token = localStorage.getItem('Authorization');
        if (!token) {
            alert('请先登录');
            return;
        }

        const response = await axios.get('http://127.0.0.1:8080/getLoginUser', {
            headers: {
                'Authorization': `${token}`, // 添加 Authorization 头
            }
        });

        if (response.data.code === 200) {
            user.username = response.data.data.username;
            user.phone = response.data.data.phone;
            editUser.username = response.data.data.username;
            editUser.phone = response.data.data.phone;
        } else {
            alert(response.data.msg || '获取用户信息失败！');
        }
    } catch (error) {
        console.error(error);
        alert('获取用户信息失败！');
    }
};

// 退出登录
const logout = async () => {
    try {
        // 获取当前的 Authorization
        const token = localStorage.getItem('Authorization');
        localStorage.removeItem('Authorization');

        // 如果有 token，则发送退出请求
        if (token) {
            const response = await axios.post(
                'http://127.0.0.1:8080/logout',
                {},
                {
                    headers: {
                        Authorization: token, // 在请求头中携带 token
                    },
                }
            );

            if (response.data.code === 200) {
                // 退出成功，清除本地存储的 Authorization
                localStorage.removeItem('Authorization');
                alert('退出登录成功');
                window.location.href = '/'; // 跳转到首页
            } else {
                alert(response.data.msg || '退出登录失败');
            }
        } else {
            alert('未登录或Token失效');
        }
    } catch (error) {
        console.error(error);
        alert('退出登录失败，请稍后再试');
    }
};

// 在组件加载时获取用户信息
onMounted(() => {
    getUserInfo();
});
</script>

<style scoped>
.user-page {
    max-width: 400px;
    margin: 20px auto;
    padding: 20px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
}

/* 设置返回按钮样式 */

.back-home {
    margin-bottom: 20px;
}

.back-home button {
    padding: 5px 10px;
    background-color: #1baeae;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.back-home button:hover {
    background-color: #17a2a2;
}

/* 其他样式 */

h2 {
    text-align: center;
    margin-bottom: 20px;
}

.user-details p {
    margin: 10px 0;
}

.action-section {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;
}

button {
    padding: 10px 20px;
    background-color: #1baeae;
    color: #fff;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

button:hover {
    background-color: #17a2a2;
}

.form-section {
    margin-top: 20px;
}

input {
    display: block;
    width: 100%;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 4px;
}
</style>
